import types

from .http_method_handle import HttpMethodHandle
from .middleware_node import MiddlewareNode


class Router(HttpMethodHandle):
    ''' 路由类 '''
    def __init__(self):
        super().__init__()

    def use(self, *args):
        '''
            注册路由中间件，可以嵌套路由
            参数:
                path: 路径前缀
                middleware: 中间件函数或Router实例

            todo: 这里其实欠考虑了 use 只传递一个参数的时候，其实也可以是一个普通的路由对象
        '''
        # args[0] 为中间件函数
        if len(args) == 1:
            # 将 args 生成为 路由对象
            handler = args[0]
            if isinstance(handler, types.FunctionType):
                thisMiddleWare = MiddlewareNode(func=handler)
            else:
                raise Exception('use方法只传递一个参数时必须是一个中间件处理函数')
        # args[0] 为 路径前缀
        elif len(args) == 2:
            path = args[0]
            handler = args[1]
            if isinstance(handler, types.FunctionType):
                thisMiddleWare = MiddlewareNode(func=handler, path=path)
            elif isinstance(handler.router, Router):
                thisMiddleWare = MiddlewareNode(router=handler.router, path=path)
            else:
                raise Exception('use方法传递两个参数时第二个参数必须为中间件处理函数或Router实例')

        # 往 subMiddlewareHeadNode链表 中注册一个 路由对象
        self._register_middleware(thisMiddleWare)

    def _register_middleware(self, middleware):
        ''' 注册中间件 '''
        if self.middleware_head_node is None:
            self.middleware_head_node = middleware
            self.middleware_end_node = middleware
        else:
            self.middleware_end_node.next = middleware
            self.middleware_end_node = middleware